import { app, BrowserWindow, ipcMain, dialog } from 'electron'
import path from 'path'
import { fileURLToPath } from 'url'
import { spawn } from 'child_process'
import Store from 'electron-store'
import ExcelJS from 'exceljs'

const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)

// 配置存储增强
const store = new Store({
  defaults: {
    lastConfig: {
      keywords: ['默认关键词'],
      searchParams: {
        searchtype: 1,
        page_index: 1,
        bidSort: 0,
        timeType: 0
      },
      schedule: {
        enabled: false,
        interval: 3600
      }
    }
  },
  migrations: {
    '1.0.1': (store) => {
      if (!store.has('lastConfig.searchParams.bidSort')) {
        store.set('lastConfig.searchParams.bidSort', 0)
      }
    }
  }
})

function createWindow() {
  const win = new BrowserWindow({
    width: 1000,
    height: 800,
    minWidth: 800,
    minHeight: 600,
    autoHideMenuBar: true, // 隐藏菜单栏
    webPreferences: {
      preload: path.join(__dirname, '../renderer/preload.js'),
      contextIsolation: true,
      sandbox: true
    }
  })

  win.loadFile('src/index.html')
  win.webContents.openDevTools({ mode: 'detach' })
}

ipcMain.handle('load-config', async () => {
  console.log('IPC load-config event received');
  try {
    const config = store.get('lastConfig');
    console.log('Loaded config:', config);
    return config;
  } catch (err) {
    console.error('加载配置错误:', err);
    throw new Error('加载配置失败: ' + err.message);
  }
});

ipcMain.handle('save-config', async (event, config) => {
  console.log('IPC save-config event received with config:', config);
  try {
    const savedConfigs = store.get('savedConfigs', []);
    savedConfigs.push(config);
    store.set('savedConfigs', savedConfigs);
    console.log('Config saved:', config);
    return true;
  } catch (err) {
    console.error('保存配置错误:', err);
    throw new Error('保存配置失败: ' + err.message);
  }
});

ipcMain.handle('load-saved-configs', async () => {
  console.log('IPC load-saved-configs event received');
  try {
    const savedConfigs = store.get('savedConfigs', []);
    console.log('Loaded saved configs:', savedConfigs);
    return savedConfigs;
  } catch (err) {
    console.error('加载已保存配置错误:', err);
    throw new Error('加载已保存配置失败: ' + err.message);
  }
});

ipcMain.handle('start-crawl', async (event, config) => {
  console.log('IPC start-crawl event received with config:', config);
  try {
    console.log('开始爬虫进程，配置:', config)
    store.set('lastConfig', config)
    const result = await runPythonProcess(config)
    console.log('爬虫进程完成，结果:', result)
    return JSON.parse(result)
  } catch (err) {
    console.error('爬虫进程错误:', err)
    throw new Error('执行失败: ' + err.message)
  }
})

ipcMain.handle('save-to-excel', async (event, results, savePath) => {
  console.log('IPC save-to-excel event received with results:', results);
  try {
    const workbook = new ExcelJS.Workbook();
    const worksheet = workbook.addWorksheet('Results');

    worksheet.columns = [
      { header: 'Title', key: 'title', width: 30 },
      { header: 'Link', key: 'link', width: 30 },
      { header: 'Date', key: 'date', width: 15 },
      { header: 'Purchaser', key: 'purchaser', width: 20 },
      { header: 'Agency', key: 'agency', width: 20 },
      { header: 'Notice Type', key: 'notice_type', width: 20 },
      { header: 'Region', key: 'region', width: 20 }
    ];

    results.forEach(result => {
      worksheet.addRow({
        title: result.title || '',
        link: result.link || '',
        date: result.date || '',
        purchaser: result.purchaser || '',
        agency: result.agency || '',
        notice_type: result.notice_type || '',
        region: result.region || ''
      });
    });

    const filePath = path.join(savePath, 'results.xlsx');
    await workbook.xlsx.writeFile(filePath);
    console.log('Results saved to Excel:', filePath);
    return true;
  } catch (err) {
    console.error('保存到Excel错误:', err);
    throw new Error('保存到Excel失败: ' + err.message);
  }
});

ipcMain.handle('select-directory', async () => {
  const result = await dialog.showOpenDialog({
    properties: ['openDirectory']
  })
  return result
})

async function runPythonProcess(config) {
  return new Promise((resolve, reject) => {
    console.log('启动 Python 进程，配置:', config)
    const pyProcess = spawn('python', ['crawler.py', JSON.stringify(config)], {
      stdio: ['pipe', 'pipe', 'pipe']
    })

    let output = ''
    const errorChunks = []

    pyProcess.stdout.on('data', (data) => {
      console.log('Python 输出:', data.toString())
      output += data.toString()
    })

    pyProcess.stderr.on('data', (data) => {
      console.error('Python 错误输出:', data.toString())
      errorChunks.push(data.toString())
    })

    pyProcess.on('close', (code) => {
      console.log('Python 进程关闭，退出码:', code)
      if (code !== 0) {
        const errorOutput = errorChunks.join('')
        reject(new Error(`进程异常退出 (${code}): ${errorOutput}`))
      } else {
        resolve(output)
      }
    })
  })
}

app.whenReady().then(() => {
  createWindow()
  app.commandLine.appendSwitch('remote-debugging-port', '9222')
})

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') app.quit()
})